const path = require("path");
const { Client } = require("ssh2");
const prompts = require("prompts");

// 服务器信息
const targetInfo = {
  host: "192.168.31.237",
  port: "22",
  username: "root",
  password: "123456",
};

// 要上传的文件列表
const targetList = [
  {
    name: "mes-basic", //应用名称
    sourceDir: "E:/chen/mes-basic-web/dist", //本地jar包路径
    sourceName: "mes-basic.jar", //jar包名称
    targetDir: "/usr/local/mes-55/mes-basic", //远程jar包路径
    shellTarget: "mes-basic.sh", //启动脚本名称
  },
  {
    name: "mes",
    sourceDir: "E:/chen/mes-basic-web/dist",
    sourceName: "mes.jar",
    targetDir: "/usr/local/mes-55/mes",
    shellTarget: "mes.sh",
  },
];

const conn = new Client();

conn.on("ready", () => {
  console.log("SSH 连接已建立.");

  conn.shell((err, stream) => {
    if (err) throw err;

    stream
      .on("close", () => {
        console.log("远程命令执行完成.");
        conn.end();
      })
      .on("data", (data) => {
        console.log("远程命令输出:", data.toString());
      });

    selectAndUploadFile(stream);
  });
});

conn.connect(targetInfo);

async function selectAndUploadFile(stream) {
  const response = await prompts({
    type: "select",
    name: "selectedFile",
    message: "请选择要上传的文件：",
    choices: targetList.map((file) => ({ title: file.name, value: file })),
  });
  const selectedFile = response.selectedFile;
  if (selectedFile) {
    const localFilePath = path.join(
      selectedFile.sourceDir,
      selectedFile.sourceName
    );
    const remoteFilePath = `${selectedFile.targetDir}/${selectedFile.sourceName}`;
    console.log("开始上传文件:", localFilePath);
    conn.sftp((err, sftp) => {
      if (err) throw err;
      sftp.fastPut(localFilePath, remoteFilePath, (err) => {
        if (err) throw err;
        console.log("文件上传成功.");
        console.log("执行远程命令:", selectedFile.shellTarget);
        stream.write(
          `cd ${selectedFile.targetDir} && chmod +x ${selectedFile.shellTarget} && ./${selectedFile.shellTarget}\n`
        );
      });
    });
  } else {
    console.log("未选择任何文件.");
    conn.end();
  }
}
